//
//  AppRouterManager.swift
//  JYRouterDemo
//
//  Created by huangguojian on 2022/6/9.
//

import UIKit
import JYRouter

/// Demo 路由管理
enum AppRouterManager: JYRouterManager {
    
    static private(set) var config: [ModuleKey : JYRouterProtocol.Type] = [:]
    
    static var whiteList: JYRouterWhiteList {
        .contain(schemes: ["app"])
    }
    
    static func handleNotOnWhiteList(_ urlStr: String) {
        guard let url = URL(string: urlStr) else { return }
        UIApplication.shared.open(url)
    }
    
    static var currentTabBarController: UITabBarController {
        getAppRootController() as! UITabBarController
    }
    
    static var currentNavigationController: UINavigationController {
        currentTabBarController.selectedViewController as! UINavigationController
    }
    
    static func getModule(from host: String) -> ModuleKey? { ModuleKey(rawValue: host) }
    
    static func showTabbarControllerAndSelect(controller: JYRouter.JYRoutable, animated: Bool) {
        guard let index = currentTabBarController.viewControllers?.firstIndex(of: controller) else { return }
        currentTabBarController.selectedIndex = index
        (currentTabBarController.selectedViewController as? UINavigationController)?.popViewController(animated: animated)
    }
    
    /// 模块名 枚举
    enum ModuleKey: String, Hashable {
        case main
    }
    
    /// 每个模块需要定义一个协议来实现跨模块调用
    static var main: AppRouterType.Type! {
        willSet {
            config[.main] = newValue
        }
    }
    
}

extension JYRouterProtocol {
   
    func link(animated: Bool = true, callBack: @escaping (JYRouterModelType) -> Void = { _ in }) {
        link(by: AppRouterManager.self, animated: animated, callBack: callBack)
    }
}

// MARK: - JYRouterModelType 扩展
extension String: JYRouterModelType {}
extension Bool: JYRouterModelType {}
